<script setup lang="ts">
import LiuUserInfo from '@/components/LiuUserInfo.vue'
import { ref, onMounted, onUnmounted } from 'vue'
import type { TbDataNews } from '@/types/thirdapi'
import type { BaseDataResult, PageBean, PageVO } from '@/types/BaseResult'
import { Api } from '@/types/Api'
import { Tools } from '@/types/Tools'
import { useRouter } from 'vue-router'
const router = useRouter()

import {
  useMessage,
  NCard,
  NSkeleton,
  NSpace,
  NPopover,
  NButton,
  NSpin,
  NEl,
  NInput,
  NTabs,
  NTabPane,
  NBackTop,
} from 'naive-ui'

const message = useMessage()

const loading = ref(false)
const firstLoad = ref(true)

//#region 查询的部分

const page = ref({ pageNumber: 1, pageSize: 10 } as PageBean)
const list = ref([] as TbDataNews[])
const queryInfo = ref({ order: 1, title: '' })

const query = () => {
  loading.value = true
  Api.get(
    `/autodata/query/news/${page.value.pageSize}/${page.value.pageNumber}/${queryInfo.value.order}`,
    { title: queryInfo.value.title },
    (data: BaseDataResult<PageVO<TbDataNews>>) => {
      loading.value = false
      if (data.success) {
        // 处理图片地址
        data.data.list.forEach((d) => {
          d.images = d.imgs.split(',')
          // d.images = []
        })
        // 数据为追加模式
        list.value = list.value.concat(data.data.list)
        page.value = data.data.pageBean
        firstLoad.value = false
        return
      }
      message.error(data.message)
    },
  )
}

const changeOrder = (order: number) => {
  queryInfo.value.order = order
  requery()
}

const search = () => {
  firstLoad.value = false
  page.value.pageNumber = 1
  list.value = []
  query()
}

const requery = () => {
  firstLoad.value = true
  page.value.pageNumber = 1
  queryInfo.value.title = ''
  list.value = []
  query()
}

const loadmore = () => {
  page.value.pageNumber++
  if (page.value.pageNumber > page.value.pageCount) {
    return
  }
  query()
}

//#endregion

//#region 滚动相关
const scroll = () => {
  // console.log('滚动了')
  if (loading.value) {
    return
  }
  // console.log('是否到底部：', isScrollToBottom())
  if (isScrollToBottom()) {
    loadmore()
  }
}

const isScrollToBottom = () => {
  const scrollTop = document.documentElement.scrollTop || window.scrollY
  const sh = document.documentElement.scrollHeight
  const ch = document.documentElement.clientHeight
  return scrollTop + ch >= sh - 100
}
//#endregion

//#region 点赞
const likeNews = (news: TbDataNews) => {
  Api.post(`/autodata/info/news/like/${news.id}`, {}, (data: BaseDataResult<number>) => {
    if (data.success) {
      news.likes = data.data
      news.praised = !news.praised
      return
    }
    message.error(data.message)
  })
}

//#endregion

//#region 详情
const toDetail = (id: number) => {
  // router.push(`/news/${id}`)
  window.open(router.resolve(`/news/${id}`).href)
}

//#endregion

onMounted(() => {
  requery()
  window.addEventListener('scroll', scroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', scroll)
})
</script>

<template>
  <NEl class="p-4 top-box">
    <div class="fs-2">新闻客户端</div>
    <div>
      <NSpace>
        <NInput v-model:value="queryInfo.title" placeholder="标题搜索"></NInput>
        <NButton type="primary" @click="search">查询</NButton>
      </NSpace>
    </div>
    <LiuUserInfo></LiuUserInfo>
  </NEl>

  <div class="pl-20 pr-20" style="width: 50vw; margin: 0px auto">
    <!-- 切换排序 -->
    <NTabs @update:value="changeOrder">
      <NTabPane name="1" tab="最新"></NTabPane>
      <NTabPane name="2" tab="高赞"></NTabPane>
      <NTabPane name="3" tab="热门"></NTabPane>
      <NTabPane name="4" tab="热评"></NTabPane>
    </NTabs>

    <!-- 骨架屏效果 -->
    <div v-if="loading && firstLoad">
      <div v-for="i in 10" :key="i" class="ml-20 mr-20 mb-2">
        <NCard>
          <NSkeleton text></NSkeleton>
          <NSkeleton text></NSkeleton>
          <div class="img-box">
            <NSkeleton text class="vimg"></NSkeleton>
            <NSkeleton text class="vimg"></NSkeleton>
            <NSkeleton text class="vimg"></NSkeleton>
          </div>
        </NCard>
      </div>
    </div>
    <!-- 数据列表 -->
    <div v-else>
      <div v-for="d in list" :key="d.id" class="mb-3">
        <!-- 多图模式 -->
        <div v-if="d.images.length > 2">
          <NCard :title="d.title">
            <div>
              <div class="fs-3" @click="toDetail(d.id)">{{ d.digest }}...</div>
              <div class="img-box">
                <div><img @click="toDetail(d.id)" :src="d.images[0]" alt="" /></div>
                <div><img @click="toDetail(d.id)" :src="d.images[1]" alt="" /></div>
                <div><img @click="toDetail(d.id)" :src="d.images[2]" alt="" /></div>
              </div>
              <div class="detail mb-2 mt-2">
                <div>
                  {{ d.source }}
                  -
                  {{ Tools.formatDate(d.createdAt, 'yyyy-MM-dd') }}
                  点击量：{{ d.hits }}
                </div>
                <div>
                  <NPopover trigger="hover">
                    <span>点赞量：{{ d.likes }}</span>
                    <template #trigger>
                      <div @click="likeNews(d)" :class="{ active: d.praised }">赞</div>
                    </template>
                  </NPopover>
                </div>
              </div>
            </div>
          </NCard>
        </div>
        <!-- 单图模式 -->
        <div v-else-if="d.images.length > 0">
          <NCard :title="d.title">
            <div class="simg-box">
              <div class="info">
                <div class="fs-3" @click="toDetail(d.id)">{{ d.digest }}...</div>
                <div class="detail mb-2 mt-2">
                  <div>
                    {{ d.source }}
                    -
                    {{ Tools.formatDate(d.createdAt, 'yyyy-MM-dd') }}
                    点击量：{{ d.hits }}
                  </div>
                  <div>
                    <NPopover trigger="hover">
                      <span>点赞量：{{ d.likes }}</span>
                      <template #trigger>
                        <div @click="likeNews(d)" :class="{ active: d.praised }">赞</div>
                      </template>
                    </NPopover>
                  </div>
                </div>
              </div>
              <div>
                <img @click="toDetail(d.id)" :src="d.images[0]" alt="" />
              </div>
            </div>
          </NCard>
        </div>
        <!-- 无图模式 -->
        <div v-else>
          <NCard :title="d.title">
            <div>
              <div class="fs-3" @click="toDetail(d.id)">{{ d.digest }}</div>
              <div class="detail mb-2 mt-2">
                <div>
                  {{ d.source }}
                  -
                  {{ Tools.formatDate(d.createdAt, 'yyyy-MM-dd') }}
                  点击量：{{ d.hits }}
                </div>
                <div>
                  <NPopover trigger="hover">
                    <span>点赞量：{{ d.likes }}</span>
                    <template #trigger>
                      <div @click="likeNews(d)" :class="{ active: d.praised }">赞</div>
                    </template>
                  </NPopover>
                </div>
              </div>
            </div>
          </NCard>
        </div>
      </div>
    </div>
  </div>

  <div class="p-4 tc" v-if="loading">
    <!-- <NButton @click="loadmore">加载更多</NButton> -->
    <span> <NSpin size="small"></NSpin>加载中... </span>
  </div>
  <div class="p-4 tc" v-if="page.pageNumber >= page.pageCount && !loading">我是有底线的</div>

  <NBackTop></NBackTop>
</template>

<style scoped lang="scss">
.top-box {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  position: sticky;
  top: 0px;
  z-index: 10;
  background-color: var(--body-color);
}

.vimg {
  display: block;
  height: 7vw;
}

.img-box {
  display: flex;
  gap: 1rem;
  > div {
    flex: 1;
  }
  img {
    display: block;
    aspect-ratio: 16/9;
    width: 100%;
    object-fit: cover;
  }
}

.simg-box {
  display: flex;
  gap: 1rem;
  img {
    display: block;
    width: 100%;
    aspect-ratio: 16/9;
    object-fit: cover;
  }
  > div:first-of-type {
    flex: 2;
  }
  > div:last-of-type {
    flex: 1;
  }
  .info {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
  }
}

.detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .active {
    color: #ff0000;
  }
}
</style>
